//
//  DNDImageView.m
//  RenamePix
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "DNDImageView.h"
#import "AppController.h"

@implementation DNDImageView

- (id)initWithFrame:(NSRect)frame;
{
	if(![super initWithFrame:frame])
		return self;
	showDragging = imageLoadFailed = NO;
	imagePath = nil;
	image = nil;
	filter = nil;
	imageType = nil;
	centeredStyle = nil;
	lastRect = NSZeroRect;
	[self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
	return self;
}

- (void)dealloc;
{
	[centeredStyle release];
	[imagePath release];
	[super dealloc];
}

- (BOOL)acceptsFirstResponder;
{
	return YES;
}
- (BOOL)becomeFirstResponder;
{
	[self setNeedsDisplay:YES];
	return YES;
}
- (BOOL)resignFirstResponder;
{
	[self setNeedsDisplay:YES];
	return YES;
}

#pragma mark Image drawing

- (void)getImageSize;
{
	NSImageRep *imageRep = [NSImageRep imageRepWithContentsOfURL:imagePath];
	imageSize = NSMakeSize([imageRep pixelsWide], [imageRep pixelsHigh]);
}

- (void)generateImageWithRect:(NSRect)rect;
{	
	if(image == nil)
	{
		imageLoadFailed = NO;
		CGImageSourceRef sourceRef = CGImageSourceCreateWithURL((CFURLRef)imagePath, nil);
		if(!sourceRef)
		{
			imageLoadFailed = YES;
			return;
		}
		NSString *sourceType = (NSString *)CGImageSourceGetType(sourceRef);
		if([sourceType isEqualToString:@"public.jpeg"])
			imageType = @"JPEG";
		else if([sourceType isEqualToString:@"public.png"])
			imageType = @"PNG";
		else if([sourceType isEqualToString:@"com.compuserve.gif"])
			imageType = @"GIF";
		else if([sourceType isEqualToString:@"public.tiff"])
			imageType = @"TIFF";
		else if([sourceType isEqualToString:@"pubic.camera-raw-image"])
			imageType = @"RAW";
		else
			imageType = @"???";
		size_t images = CGImageSourceGetCount(sourceRef);
		if(images > 1)
		{
			// Handle animated GIF
		}
		CGImageRef imageRef = CGImageSourceCreateImageAtIndex(sourceRef, 0, NULL);
		CFRelease(sourceRef);
		image = [CIImage imageWithCGImage:imageRef];
		CFRelease(imageRef);
	}
	
	//Stretch the image
	float height = imageSize.height;
	float width = imageSize.width;
	float rectWidth = NSWidth(rect);
	float rectHeight = NSHeight(rect);
	float scale = 1.0;
	
	// Stretch width
	scale = rectWidth / width;
	width = rectWidth;
	height *= scale;
	drawRect = CGRectMake(0, (rectHeight - height) / 2.0, width, height);
	if(height > rectHeight) // Too tall
	{
		height = imageSize.height;
		scale = rectHeight / height;
		height = rectHeight;
		width = imageSize.width * scale;
		drawRect = CGRectMake((rectWidth- width) / 2.0, 0, width, height);
	}

	if(filter == nil)
	{
		filter = [CIFilter filterWithName:@"CILanczosScaleTransform" keysAndValues:@"inputImage", image, nil];
		[filter setValue:[NSNumber numberWithFloat:1.0] forKey:@"inputAspectRatio"];
	}
	[filter setValue:[NSNumber numberWithFloat:scale] forKey:@"inputScale"];
	image = [filter valueForKey:@"outputImage"];
}

- (void)drawMessageCentered:(NSString *)message inRect:(NSRect)rect;
{
	if(centeredStyle == nil)
	{
		NSMutableParagraphStyle *mutableCenteredStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
		[mutableCenteredStyle setAlignment:NSCenterTextAlignment];
		centeredStyle = [mutableCenteredStyle copy];
	}
	[message drawInRect:NSMakeRect(0, NSHeight(rect) / 2, NSWidth(rect), 20) withAttributes:[NSDictionary dictionaryWithObjectsAndKeys:centeredStyle, NSParagraphStyleAttributeName, nil]];
}

- (void)drawRect:(NSRect)rect;
{
	[super drawRect:rect];
	if(imagePath == nil)
	{
		[self drawMessageCentered:@"Open some files!" inRect:rect];
		return;
	}
	
	if(image == nil || !NSEqualRects(rect, lastRect))
		[self generateImageWithRect:rect];
	if(imageLoadFailed)
	{
		[self drawMessageCentered:@"Image load failed" inRect:rect];
		return;
	}
	lastRect = rect;
	
	[[NSColor blackColor] set];
	NSRectFill(rect);
	CIContext *context = [[NSGraphicsContext currentContext] CIContext];
	CGRect cg = CGRectMake(NSMinX(rect), NSMinY(rect), NSWidth(rect), NSHeight(rect));
	if(context != nil)
		[context drawImage:image atPoint:drawRect.origin fromRect:cg];
}

#pragma mark -
#pragma mark Accessors

- (NSString *)imageDescription;
{
	return [NSString stringWithFormat:@"%@ Image %.0fx%.0f", imageType, imageSize.width, imageSize.height, nil];
}

- (void)setAppController:(AppController *)newAppController;
{
	appController = newAppController;
}

- (void)setImagePath:(NSURL *)aImagePath;
{
	aImagePath = [aImagePath copy];
	[imagePath release];
	imagePath = aImagePath;
	image = nil;
	imageType = nil;
	filter = nil;
	[self getImageSize];
	[self display]; // Load now for image type
}

#pragma mark -
#pragma mark Mouse events

/* - (void)mouseDown:(NSEvent *)theEvent;
{
	// Zoom in
}

- (void)rightMouseDown:(NSEvent *)theEvent;
{
	// Zoom out
} */

#pragma mark -
#pragma mark Drag and Drop

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender;
{
	NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
	NSPasteboard *pboard = [sender draggingPasteboard];
	if([[pboard types] containsObject:NSFilenamesPboardType])
	{
		if(sourceDragMask & NSDragOperationGeneric)
		{
			showDragging = YES;
			[self display];
			return NSDragOperationGeneric;
		}
	}
	return NSDragOperationNone;
}

- (NSDragOperation)draggingExited:(id <NSDraggingInfo>)sender;
{
	showDragging = NO;
	[self display];
	return NSDragOperationNone;
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender;
{
	showDragging = NO;
	[self display];
	NSPasteboard *pboard = [sender draggingPasteboard];
	if([[pboard types] containsObject:NSFilenamesPboardType])
	{
		NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
		[appController openFiles:files];
	}
	return YES;
}

#pragma mark -

@end